import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { ElMessage } from 'element-plus'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  timeout: 3000,
  headers: { 'X-Custom-Header': 'foobar' }
})

const noPromissionApi = ['/api/login']

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    if (noPromissionApi.includes(config.url || '')) return config
    if (!store.state.baseInfo.userInfo) {
      router.replace('/login')
      ElMessage.error('无token,请重新登录')
      return
    }
    config.headers = {
      ...config.headers,
      authorization: store.state.baseInfo.userInfo.token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    const data = response.data
    if (data.code === 200) {
      if (data.message) ElMessage.success(data.message)
      return data
    } else if (data.code === 404) {
      store.commit('baseInfo/userInfo', null)
      router.push('/login')
    }
    ElMessage.error(data.message)
    console.error(new Error(data))
  },
  function (error) {
    ElMessage.error('网络请求错误')
    return Promise.reject(error)
  }
)

export default request
